package models

import (
	"log"

	"zhihu-api/config"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

func SetupDB() {
	var err error

	dsn := config.GetDSN()
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})

	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	// 自动迁移模式
	err = DB.AutoMigrate(
		&User{},
		&Topic{},
		&Question{},
		&Answer{},
		&Comment{},
		&UserFollowing{},
		&UserFollowingTopic{},
		&UserFollowingQuestion{},
		&QuestionTopic{},
		&UserLikingAnswer{},
		&UserCollectingAnswer{},
	)

	if err != nil {
		log.Fatalf("Failed to auto migrate: %v", err)
	}
}
